# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         user
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019-11-03
# -------------------------------------------------------------------------------

from rest_framework import serializers
from apps.BasicAuthService.models import User
from apps.BasicAuthService.serializers import BaseListSerializer, BaseSerializer

__all__ = ['UserListSerializer', 'UserSerializer']


class UserListSerializer(BaseListSerializer):
    roles = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()

    def get_roles(self, obj):
        roles = obj.roles.filter(is_deleted=False)
        return [{'id': item.id, 'name': item.name, 'code': item.code} for item in roles] if roles else []

    def get_permissions(self, obj):
        permissions = obj.permissions.filter(is_deleted=False).order_by('sort')
        return [{'id': item.id, 'name': item.name, 'code': item.code, 'types': item.types} for item in
                permissions] if permissions else []

    class Meta:
        model = User
        fields = ('id', 'username', 'real_name', 'phone', 'gender', 'email', 'is_active', 'last_login', 'create_time',
                  'update_time', 'remark', 'roles', 'permissions', 'modifier', 'is_system')


class UserSerializer(BaseSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'real_name', 'phone', 'gender', 'email', 'is_active', 'is_deleted', 'last_login',
                  'create_time', 'update_time', 'remark', 'roles', 'permissions', 'password', 'modifier')
        extra_kwargs = {
            'password': {'write_only': True}
        }
